var ctx=window.daijia.ctx;

function chColor(mycolor){
 	document.getElementById("contentBody").style.color = mycolor;
 }
 function backgroundColor(mycolor2){
	 document.getElementById("backage_color").style.backgroundColor = mycolor2;
 }

 
 function backgroundImage(s,i){
	 $("#image").attr("src",s);
	 $("#imgsUrl").val(i);
 }

$(document).ready(function(){
	
	$("#start").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', minView: 'month', pickDate: true, pickTime: false, inputMask: false, autoclose: true, startDate: new Date()});
	$("#end").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', minView: 'month', pickDate: true, pickTime: false, inputMask: false, autoclose: true, startDate: new Date()});
	$('#backgroudColor').minicolors({
		theme: 'bootstrap' 
	}); 
	 
	
	$('#companyIds').multiselect({
		enableFiltering: true,
	    includeSelectAllOption: true,
	    selectAllText: '全部',
	    selectAllJustVisible: true,
	    maxHeight:300,
	    buttonWidth: '100%',
	    nonSelectedText: '请选择所属公司',
	    nSelectedText: ' - 已选择',
	    numberDisplayed: 4,
	    allSelectedText: '已选择全部'
	});
	
	$('#gradeIds').multiselect({
		enableFiltering: true,
	    includeSelectAllOption: true,
	    selectAllText: '全部',
	    selectAllJustVisible: true,
	    maxHeight:300,
	    buttonWidth: '100%',
	    nonSelectedText: '不限制客户等级',
	    nSelectedText: ' - 已选择',
	    numberDisplayed: 4,
	    allSelectedText: '已选择全部'
	});
	
	KindEditor.ready(function(K) {
		K.create('#activityContent',{
			filterMode : false,
			uploadJson : ctx+'/common/kindeditor/fileupload',
			allowUpload : true,
			fileManagerJson : ctx+'/common/kindeditor/filemanager',
			allowFileManager : true,
			height:400,
			width:'100%',
			resizeType:0,
			afterChange : function() {
				$("#contentBody").html($("#activityContent").val());
				}, 
			
			items:['source', '|', 'fullscreen', 'undo', 'redo',  
			        '|', 'justifyleft', 'justifycenter', 'justifyright',
			       'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript','forecolor',
			       'superscript', '|', 'selectall', '-',
			       'title', 'fontname', 'fontsize', '|', 'textcolor', 'bgcolor', 'bold',
			       'italic', 'underline', 'strikethrough', 'removeformat', '|','advtable', 'hr'],
			afterCreate : function() {
				var self = this;
				K.ctrl(document, 13, function() {
					self.sync();
				});
				K.ctrl(self.edit.doc, 13, function() {
					self.sync();
				});
			},
			afterBlur:function(){ 
				this.sync();
			}
		});
	});
	
	
	
	$(document).on("click",".img",function(){
		$(".img").each(function(index,element){
			$(element).css("border","");
		});
		$(this).css("border","2px solid red");
		$(this).css("border-color","#394249");
		backgroundImage($(this).attr("src"),$(this).attr("bath-src"));
		backgroundColor($(this).attr("backgroud"));
		
	});
	
	$("#shareImage_btn").click(function(){
		$("#activityImage").click();				
	});
	
	$(document).on('change','#activityImage',function(){
		if($.trim($(this).val())){
		 	$.ajaxFileUpload({
                url:ctx+'/common/uploadimg.json',
                secureuri:false,
                fileElementId:'activityImage',
                dataType: 'json',
                success: function (data) {

                	if(data.success){
                		$.scojs_message("上传成功", $.scojs_message.TYPE_OK);
                    	
                		$("#myImage").remove();
                		$("#custom").append("<img id='myImage' class='img' src="+ctx+"/"+data.url+" bath-src="+data.url+" width='80' height='100' />");
                	}
                	else{
                		$.scojs_message(result.msg, $.scojs_message.TYPE_ERROR);
                	}
                }
            });
		}
	});	
	
	$(document).on('click','#myImage',function(){
		$("#backgroudColor_div").fadeIn(200);
	});
	$(document).on('click','img[name=hide]',function(){
		$("#backgroudColor_div").hide();
	});
	
	$("#tab2").hover(function(){ 
	$("#shareImage_btn").fadeIn(0); 
	$("#shareImage_btn2").fadeOut(0); },
	function(){
	$("#shareImage_btn2").fadeIn(0); 
	$("#shareImage_btn").fadeOut(0); }); 
		
	
	//添加优惠券
	$("#add_coupon_rule").click(function(){
		var element="<div class='form-group coupon_div'>"+
		                    "<label class='col-sm-3 control-label'></label>"+
		                    "<div class='col-sm-3'>"+
		                    	$("#first_coupon_div select").clone().prop("outerHTML")+
		                    "</div>"+
		                    "<label style='float:left;' class='control-label'><em>*</em>数量：</label>"+
		                    "<div class='col-sm-1'>"+
		                    	"<input class='form-control couponAmount' type='number' min='1' value='1'/>"+
		                    "</div>"+
		                    "<div class='col-sm-1'>"+
		                    	"<button type='button' class='btn btn-default delete_coupon_rule'>"+
								  "<span class='glyphicon glyphicon-remove-sign'></span> 删除"+
								"</button>"+
		                    "</div>"+
	                    "</div>";
		$("#first_coupon_div").after(element);
	});
	
	//删除优惠券
	$(document).on("click",".delete_coupon_rule",function(){
		$(this).parent().parent().remove();
	});
	
	$("#submit_button").click(function(){
		
		if($("#completeTimes").val()==0){
			$("#completeTimes").val("");
		}
		
		if($("#imgsUrl").val().indexOf("assets/img/phonegift_1.png")!=-1){
			$("#backgroudColor").val($("#phonegift_1").attr("backgroud"));
		}
		else if($("#imgsUrl").val().indexOf("assets/img/phonegift_2.jpg")!=-1){
			$("#backgroudColor").val($("#phonegift_2").attr("backgroud"));
		}
		else if($("#imgsUrl").val().indexOf("assets/img/phonegift_3.jpg")!=-1){
			$("#backgroudColor").val($("#phonegift_3").attr("backgroud"));
		}
		
		if(main){
			if($("#companyIds").val()==null){
				$.scojs_message("请选择所属公司", $.scojs_message.TYPE_ERROR);
				return false;
			}
		}
		/*if($("#gradeIds").val()==null){
			$.scojs_message("请选择客户等级", $.scojs_message.TYPE_ERROR);
			return false;
		}*/
		
		if(""!=$("#orderType").val()){
			if(""==$("#completeTimes").val()){
				$.scojs_message("请输入每完成订单次数", $.scojs_message.TYPE_ERROR);
				return false;
			}
		}
		
		if($("#activityType").val()=="cash"){
			var reg=/^(-?\d+)?$/;
			if($("#money").val()=="" || !reg.test($("#money").val())){
		       $.scojs_message('无效的金额！', $.scojs_message.TYPE_ERROR);
		       return false;
		    }
		}
		else if($("#activityType").val()=="coupon"){
			var flag=false;
			var currentSelect;
			$(".couponRule_select").each(function(index,element){
				if($(element).val()==""){
					flag=true;
					currentSelect=element;
					return false;
				}
			})
			if(flag){
				$(currentSelect).focus();
				$.scojs_message('请选择一张优惠券！', $.scojs_message.TYPE_ERROR);
			    return false;
			}
		}
		
		if($("#restriction").val()==""){
			$.scojs_message("请填写限制参与次数", $.scojs_message.TYPE_ERROR);
			return false;
		}
		if($("#start").val()==""){
			$.scojs_message("请填写或选择开始时间", $.scojs_message.TYPE_ERROR);
			return false;
		}
		if($("#end").val()!=""){
			if($("#start").val()>$("#end").val()){
				 $.scojs_message("起始日期不能大于结束日期", $.scojs_message.TYPE_ERROR);
				 return false;
			}
		}
		
		if($("#imgsUrl").val()==""){
			$.scojs_message("请点击选择要上传活动图片", $.scojs_message.TYPE_ERROR);
			return false;
		}
		if($("#backgroudColor").val()==""){
			$.scojs_message("请选择背景颜色", $.scojs_message.TYPE_ERROR);
			return false;
		}
		
		
		
		if(main){
			var companyNames=[];
			$("#companyIds option:selected").each(function(index,element){
				companyNames.push($(element).text());
			});
			$("#companyNames").val(companyNames.join(","));
		}
		
		
		
		var gradeNames=[];
		if($("#gradeIds option").size()==$("#gradeIds option:selected").size()){
			$("#gradeIds").val("");
			$("#gradeNames").val("");
			
		}else{
			$("#gradeIds option:selected").each(function(index,element){
				gradeNames.push($(element).text());
			});
			$("#gradeNames").val(gradeNames.join(","));
		}
		
		
		
		var couponIds=[];
		var couponAmounts=[];
		var eachLimit=[];
		var numerAll=[];
		$(".coupon_div").each(function(index,element){
			couponIds.push($(element).find(".couponRule_select").val());
			couponAmounts.push($(element).find(".couponAmount").val());
			eachLimit.push($(element).find(".couponRule_select option:selected").attr("eachLimit"));
			numerAll.push($(element).find(".couponRule_select option:selected").attr("numerAll"));
		});
		$("#couponIds").val(couponIds.join(","));
		$("#couponAmounts").val(couponAmounts.join(","));
		
		
		var isRedo = false;
		var s = couponIds.join(",")+","; 
		for(var i=0;i<couponIds.length;i++) { 
			if(s.replace(couponIds[i]+",","").indexOf(couponIds[i]+",")>-1) { 
				isRedo = true;
			}
		}
		if(isRedo){
			$.scojs_message("优惠券重复，请重新选择！", $.scojs_message.TYPE_ERROR);
			return false;
		}
		
		
		for (var i = 0; i < couponAmounts.length; i++) {
			if(parseInt(couponAmounts[i])>10){
				$.scojs_message("优惠券输入数量不能大于10", $.scojs_message.TYPE_ERROR);
				$($(".coupon_div")[i]).find(".couponAmount").focus();
				return false;
			}
			if(parseInt(eachLimit[i])!=0){
				if(parseInt(couponAmounts[i])>parseInt(eachLimit[i])){
					$.scojs_message("该优惠券输入数量不能大于每人限领数量", $.scojs_message.TYPE_ERROR);
					$($(".coupon_div")[i]).find(".couponAmount").focus();
					return false;
				}
			}
			if(parseInt(couponAmounts[i])>parseInt(numerAll[i])){
				$.scojs_message("该优惠券输入数量不能大于优惠券规则总数量", $.scojs_message.TYPE_ERROR);
				$($(".coupon_div")[i]).find(".couponAmount").focus();
				return false;
			}
			
		}
		
		$.post(ctx+'/activity/create',$("#submit_form").serialize(),function(data){
			if(data.success){
				$.scojs_message("创建成功", $.scojs_message.TYPE_OK);
				window.location=ctx+"/activity/list?event="+$("#activityEvent").val()+"&type="+$("#activityType").val()+"";
			}
			else{
				$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
				$("#submit_button").attr("disabled",false);
			}
		});
		
	});
	
	

});

